package club.banyuan.controller;

import club.banyuan.bean.Blog;
import club.banyuan.bean.Comment;
import club.banyuan.service.BlogService;
import club.banyuan.service.CommentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;
import java.util.List;

@Controller
public class BlogController {
    private BlogService blogService;
    private CommentService commentService;

    @Autowired
    public BlogController(BlogService blogService,
                          CommentService commentService) {
        this.blogService = blogService;
        this.commentService=commentService;
    }

    @GetMapping("/blog/{id}")
    public String getBlog(Model model,
                          @PathVariable Integer id){
        Blog blog=blogService.getBlogById(id);
        List<Comment> comments = commentService.getCommentsByBlogId(id);
        model.addAttribute("blog",blog);
        model.addAttribute("comments",comments);
        return "item";
    }

    @GetMapping("/admin/blog")
    public String adminBlogs(){
        return "redirect:/admin-blogs";
    }

    @GetMapping("/admin-blogs")
    public String adminBlogsList(Model model,
                                 @RequestParam(name = "page", defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                 Principal principal){
        String username = principal.getName();
        // UserDetails user = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // PageInfo<Blog> blogs = blogService.getBlogsByUser(pageNum,pageSize,user.getUsername());
        PageInfo<Blog> blogs = blogService.getBlogsByUser(pageNum,pageSize, username);
        model.addAttribute("blogs",blogs);
        return "admin-blogs";
    }
//    @GetMapping("/admin-blogs")
//    public String admin_blogs(@ModelAttribute("newUser") User user) {
//        return "admin-blogs";
//    }
}
